﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using MISAPP.Classify.DataAccess;
using Microsoft.Office.Interop.PowerPoint;

namespace MISAPP.Classify.Service
{
    public class Service_Presentation:Service_Matrix    
    {
        /// <summary>
        /// PPT經委會→上傳經委會季追蹤報告檔
        /// 上傳經委會預算(投影片)→PPT經委會預算報告
        /// </summary>
        public enum PPTType
        {
            PPT經委會=1, PPT經委會預算報告,PPT明年度預算,PPT預算執行分析附件
        };

        protected DA_Presentation da = null;
        protected DA_Presentation DA
        {
            get
            {
                if (da == null)
                {
                    da = new DA_Presentation();
                }
                return da;
            }
        }
        protected Application PPT = null;

        public Service_Presentation()
        {
            PPT = new Application();
            team = "Presentation";
        }

        public bool InsertPresentation(string p_misGroup,string p_user_id
            ,string p_fileName,PPTType p_type)
        {
            int count = GetSlidesCount(p_fileName);
            return DA.Insert(p_misGroup, p_user_id, p_fileName
                ,count.ToString(),((int)p_type).ToString()) ;
        }

        public DataTable GetData(PPTType p_type)
        {
            return DA.GetData(((int)p_type).ToString());
        }

        /*
         * 1.先開啟已DRAFT 的備份檔案，要把其它的檔案合併到這裏來
         * 2.取回目前已經上傳的檔案。依順序取出來，組別的順序放在MISPRARMETER 中，
         *      可以不用改程式，而去改取檔案的順序
         * 3.再依MISPARAMETER 中所定義的開檔順序，依序開啟檔案。
         * 4.當使用完畢後，要先把組別的檔案關掉。
         * 5.當所有的檔案都合併後，SAVE & CLOSE
         */
        protected void openFile(string p_file)
        {
            try
            {
                PPT = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
                PPT.Presentations.Open(p_file,Microsoft.Office.Core.MsoTriState.msoFalse
                   ,Microsoft.Office.Core.MsoTriState.msoFalse
                   ,Microsoft.Office.Core.MsoTriState.msoFalse);
            }
            catch (Exception ex)
            { 
                throw new Exception(string.Format("開啟投影片檔出現錯誤:{0}",ex.Message));
            }
            
        }

        public void MergePresentation(string p_file, PPTType p_type)
        {
            DataTable dt = GetData(p_type);
            openFile(p_file); //open DRAFT 
            List<Squared> grp = GetGroupSeq(((int)p_type).ToString());
            Squared sq = grp[0];
            int pos;
            pos = 2;
            Microsoft.Office.Interop.PowerPoint.Presentation _presentation = 
                PPT.Presentations[1] as 
                Microsoft.Office.Interop.PowerPoint.Presentation;
            Microsoft.Office.Interop.PowerPoint.Slides _slides = null;
            foreach (string rng in sq.Ranges)
            {
                DataRow[] select = (from aa in dt.AsEnumerable()
                                    where aa.Field<string>("MISGroup") == rng
                                    select aa).ToArray<DataRow>();
                if (select.Length > 0)
                {
                    //_presentation = PPT.Presentations[1]
                    //    as Microsoft.Office.Interop.PowerPoint.Presentation;
                    if (System.IO.File.Exists(select[0]["ppt"].ToString()))
                    {
                        PPT.Presentations.Open(select[0]["ppt"].ToString()
                            , Microsoft.Office.Core.MsoTriState.msoFalse
                            , Microsoft.Office.Core.MsoTriState.msoFalse
                            , Microsoft.Office.Core.MsoTriState.msoFalse);
                        _slides = PPT.Presentations[2].Slides as 
                            Microsoft.Office.Interop.PowerPoint.Slides;
                        foreach (Microsoft.Office.Interop.PowerPoint.Slide
                            _slide in _slides)
                        {
                            _slide.Copy();
                            Microsoft.Office.Interop.PowerPoint.SlideRange slideRng
                                = _presentation.Slides.Paste(pos);
                            slideRng.ColorScheme = _slide.ColorScheme;
                            slideRng.Design = _slide.Design;
                            pos ++;
                        }
                        PPT.Presentations[2].Close();
                    }
                }
            }
            closePPT(System.IO.Path.GetFileName(p_file), true);
        }

        /// <summary>
        /// 原本用InsertFromFile 後來改用上面的用foreach slide
        /// </summary>
        /// <param name="p_file"></param>
        /// <param name="p_type"></param>
        /// <param name="p_old"></param>
        public void MergePresentation(string p_file,PPTType p_type, int p_old)
        {
            DataTable dt = GetData(p_type);
            openFile(p_file); //open DRAFT 
            List<Squared> grp = GetGroupSeq(((int)p_type).ToString());
            Squared sq = grp[0];
            int pos;
            pos = 1;
            Microsoft.Office.Interop.PowerPoint.Presentation _presentation = null;
            foreach (string rng in sq.Ranges)
            {
                DataRow[] select = (from aa in dt.AsEnumerable()
                                    where aa.Field<string>("MISGroup") == rng
                                    select aa).ToArray<DataRow>();
                if (select.Length > 0)
                {
                    _presentation = PPT.Presentations[1]
                        as Microsoft.Office.Interop.PowerPoint.Presentation;
                    if (System.IO.File.Exists(select[0]["ppt"].ToString()))
                    {
                        pos += _presentation.Slides.InsertFromFile(select[0]["ppt"].ToString()
                            , pos, 1
                            , Convert.ToInt16(select[0]["pptCount"].ToString()));
                    }                    
                }
            }
           // _presentation.Slides[pos+1].Delete(); //因為我的template 有一張空白的母片，而合併後這張空白片會到最後去，所以要踢掉它
            closePPT(System.IO.Path.GetFileName(p_file),true);
        }

        protected void closePPT(string p_name,bool p_save)
        {
            for (int i = 1; i <= PPT.Presentations.Count; i++)
            {                
                if (PPT.Presentations[i].Name.Equals(p_name))
                {
                    if (p_save == true)
                    {
                        PPT.Presentations[i].Save();
                    }
                }
                PPT.Presentations[i].Close();    
            }            
        }

        public int GetSlidesCount(string p_file)
        {            
            openFile(p_file);
            int slideCount = PPT.Presentations[1].Slides.Count;
            closePPT(p_file, false);
            return slideCount;
        }

        public void ReleasePPT()
        {
            Utility.ReleaseCOMObject(PPT);
        }

        public List<Squared> GetGroupSeq(string p_level)
        {
            return GetParameterValue(DA, new object[] { p_level, team });
        }
    }
}
